import { ApiRes } from '@/types/data'
import { userItem } from '@/types/user'
import request from '@/utils/request'
import { getUserList, setUserList } from '@/utils/storage'
import { defineStore } from 'pinia'
export default defineStore('user', {
  state: () => ({
    userList: getUserList(),
  }),
  actions: {
    async getLoginList(account: string, password: string) {
      const res = await request.post<ApiRes<userItem>>('/login', {
        account,
        password,
      })
      this.userList = res.data.result
      setUserList(res.data.result)
    },
    // 获取手机验证码
    async sendMobileMsg(mobile: string) {
      await request.get('/login/code', {
        params: {
          mobile,
        },
      })
    },
    async mobileLogin(mobile: string, code: string) {
      const res = await request.post<ApiRes<userItem>>('/login/code', {
        mobile,
        code,
      })
      this.userList = res.data.result
      setUserList(res.data.result)
    },
    //  source: 1为pc，2为webapp，3为微信小程序, 4为Android, 5为ios, 6为qq, 7为微信
    async qqLogin(openId: string) {
      const res = await request.post<ApiRes<userItem>>('/login/social', {
        unionId: openId,
        source: 6,
      })
      // 1. 保存用户信息到 state 中
      console.log(res)

      // this.userList = res.data.result
      // setUserList(res.data.result)
    },
    //账号绑定
    async getSocalBind(openId: string, mobile: string, code: string) {
      const res = await request.post('/login/social/bind', {
        unionld: openId,
        mobile,
        code,
      })
    },
    // 发送已有账号的短信
    async sendQQMobileMsg(mobile: string) {
      const res = await request.get('/login/social/code', {
        params: {
          mobile,
        },
      })
      this.userList = res.data.result
      setUserList(res.data.result)
    },
    // 获取短信验证码
    // 绑定qq的短信验证码
    async sendQQPathMsg(mobile: string) {
      await request.get('/register/code', {
        params: {
          mobile,
        },
      })
    },

    async qqPatchLogin(
      openId: string,
      account: string,
      mobile: string,
      code: string,
      password: string
    ) {
      const res = await request.post<ApiRes<userItem>>(
        `/login/social/${openId}/complement`,
        {
          account,
          mobile,
          code,
          password,
        }
      )
      // 1. 保存用户信息到 state 中
      this.userList = res.data.result
      setUserList(res.data.result)
    },
  },
})
